
require 'plasma_applet'
require 'korundum4'

require 'yaml'
require 'logger'

require 'sms_sender.rb'
require 'addressbook.rb'
require 'configuration_dialog.rb'


 
module SmsWidget
  class Main < PlasmaScripting::Applet
  
  slots :configAccepted, :showConfigurationInterface
  signals :textChanged, 'currentIndexChanged(const QString&)', 'textEdited(const QString &)'

    @@logger = Logger.new(STDOUT)

    #member vars
    @config
    @login_name
    @password
    @provider_list
    @yaml
    @provider_list_yaml
    
    @mainlayout
    @label_status
    @message
    @input_number
    @status_icon
    @provider_combobox
    @label_to
    @input_own_number
    @own_number
    @label_help
    @provider_label
    
    @sms_sender
    @addressbook
    @counter
    @config_dialog

    @version

    #constructor
    def initialize(parent, args = nil)
      super
      setHasConfigurationInterface(true)
    end

    def init
      set_minimum_size 300, 280

      yml_path = package.path() + "contents/code/provider_list.yml"
      @provider_list_yaml = YAML::load( File.open(yml_path) )

      #SmsWidget::Main.logger.info "provider_list to yaml:\n #{@provider_list_yaml.to_yaml}"

      # initialize configuration
      @config = self.config()

      # read config
      SmsWidget::Main.logger.info "Reading config..."

      @login_name = @config.readEntry("login", "")
      SmsWidget::Main.logger.info "login: #{@login_name}"

      @password = @config.readEntry("password", "")
      SmsWidget::Main.logger.info "pw: "+ "*"*@password.length

      @own_number = @config.readEntry("own_number", "")
      SmsWidget::Main.logger.info "own_number: #{@own_number}"

      @provider = @config.readEntry("provider_new", "")
      SmsWidget::Main.logger.info "provider_new: #{@provider}"

      @version = @config.readEntry("version", 0.2)

      if @provider.eql? ""
        self.showConfigurationInterface()
      end

      @counter = @config.readEntry("counter", 0)
      SmsWidget::Main.logger.info "counter: #{@counter}"

      @yaml = YAML.load(@config.readEntry("yaml", ""))
      #SmsWidget::Main.logger.info "yaml: #{@yaml.inspect}"
      
      # initialize sender object
      @sms_sender = SmsSender.new self
      
      # addressbook
      @addressbook = AddressBook.new self

      # setup layout
      @mainlayout = Qt::GraphicsLinearLayout.new Qt::Vertical, self
      layout = @mainlayout
      self.layout = layout

      @provider_label = Plasma::Label.new self
      @provider_label.text = @provider
      @provider_label.setStyleSheet("font-weight: bold; font-size: 18px;")

      layout.add_item @provider_label
 
      @label_to = Plasma::Label.new self
      @label_to.text = ""
      @label_to.nativeWidget().setFixedHeight(20)
      layout.add_item @label_to
      
      number_layout = Qt::GraphicsLinearLayout.new Qt::Horizontal, @mainlayout
 
      @input_number = Plasma::LineEdit.new self
      @input_number.nativeWidget().setToolTip("Enter one of your contact's name and press Enter.")
      @input_number.nativeWidget().setCompletionMode(KDE::GlobalSettings::CompletionAuto)

      @input_number.nativeWidget().setClickMessage("Number or contact name")

      @input_number.setZValue(1)

      
      number_layout.add_item @input_number
      button_addressbook = Plasma::PushButton.new
      ab_icon = package.filePath("images", "ab-icon.png")
      button_addressbook.setImage(ab_icon)
      button_addressbook.setStyleSheet("width: 15px")
      #button_addressbook.text = 'addr'
      number_layout.add_item button_addressbook

      layout.add_item number_layout
 
      @message = Plasma::TextEdit.new self

      layout.add_item @message

      @input_number.setZValue((@message.zValue)+1)
      
      button_send = Plasma::PushButton.new self
      button_send.text = 'Send'

      layout.add_item button_send
      
      @label_status = Plasma::Label.new self
      @label_status.nativeWidget().setMinimumHeight(40)
      @label_status.setStyleSheet("font-weight: bold;")
      self.set_status_msg("Ready.")
      layout.add_item @label_status   

      button_send.connect(SIGNAL(:clicked)) do
        self.set_status_msg("sending...")
        @sms_sender.send(@input_number.text, @message.nativeWidget.toPlainText)
        #self.setBusy(true)
      end
      
      button_addressbook.connect(SIGNAL(:clicked)) do
        #self.setStatusMsg("Adressbuch.")
        @addressbook.setup_ui()
      end
      
      @message.connect(SIGNAL(:textChanged)) do
        self.update_counter
      end

      @input_number.connect(SIGNAL(:returnPressed)) do
        self.search_contact @input_number.text
      end

      @input_number.connect(SIGNAL("textEdited(const QString &)")) do
        self.reload_number_input_hints(@input_number.text)
      end

    end

    def self.logger
      @@logger
    end

  def createConfigurationInterface(parent)

    @config_dialog = ConfigurationDialog.new parent, self

    connect(parent, SIGNAL(:applyClicked), self, SLOT(:configAccepted))
    connect(parent, SIGNAL(:okClicked), self, SLOT(:configAccepted))

  end

    def configAccepted()
      SmsWidget::Main.logger.debug "configAccepted"

      @config.writeEntry("login", config_dialog().input_login.text())

      @config.writeEntry("password", config_dialog().input_password.text())

      @config.writeEntry("own_number", config_dialog().input_own_number.text())

      @config.writeEntry("provider_new", config_dialog().provider_combobox.currentText())

      @config.writeEntry("version", @version)

      @sms_sender.load_provider()
      @provider_label.text = provider

      @config.sync()

      constraintsEvent(Plasma::SizeConstraint)
      update()
      emit configNeedsSaving
    end
    
    def sms_sent()
      @counter = @counter + 1
      @config.writeEntry("counter", @counter)
      self.set_status_msg("SMS sent. (#{@counter} sent so far)")
      SmsWidget::Main.logger.info "SMS sent. (#{@counter} sent so far)"
    end

    def sms_not_sent(reason)
      self.set_status_msg("SMS NOT sent! #{reason}")
      SmsWidget::Main.logger.info "SMS NOT sent! #{reason}"
    end

    def set_status_msg(msg)
      @label_status.setText(msg)
      #@status_icon.setLabel(msg)
    end
    
    def update_counter() # update counter while typing
      #SmsWidget::Main.logger.info "updateCounter()"
      chars = @message.nativeWidget.toPlainText.length
      charsToUse = 160-chars
      set_status_msg("#{chars} characters used so far.")
    end
    
    def get_config()
      @config
    end

    def provider()
      @config.readEntry("provider_new", "") #provider string, e.g. OrangeCH
    end

    def login_name()
      @config.readEntry("login", "")
    end

    def password()
      @config.readEntry("password", "")
    end

    def own_number()
      @config.readEntry("own_number", "")
    end

    def search_contact(name) # search contact, feature used in number input field.
      SmsWidget::Main.logger.info "search for name: #{name}"
      contact_names = @addressbook.get_contact_names
      contacts = @addressbook.get_contacts
      if contact_names.include?(name)
        @input_number.setText(contacts[name])
        self.set_to_msg("Send it to #{name}")
        SmsWidget::Main.logger.info "Number found: #{contacts[name]}"
      else 
        @input_number.setText("")
        self.set_to_msg("Number (search not found)")
        #@input_number.nativeWidget().setCompletedText("Contact not found!", true)
        SmsWidget::Main.logger.info "Number not found."
      end
      
    end

    def set_to_msg(msg)
      @label_to.setText(msg)
    end

    def get_provider_names()
      @provider_list_yaml.keys
    end

    def provider_list_yaml()
      @provider_list_yaml
    end

    def provider_list()
      self.provider_list_yaml
    end

    def addressbook()
      @addressbook
    end

    def config_dialog()
      @config_dialog
    end

    def reload_number_input_hints(searchtext)
      unless searchtext.eql? ""
        names = self.addressbook.get_contact_names
        matches = names.select {|v| v =~ /#{searchtext}/}
        @input_number.nativeWidget().setCompletedItems(matches, true)
        SmsWidget::Main.logger.debug "reload number input hints: #{searchtext}"
      end
      
    end

    

  end
end